package com.bdqn.config;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * MyShiroRealm
 * 自定义 Realm
 * @author f
 * @since 2021/12/11
 * 自定义 Realm 需要继承 AuthorizingRealm 类，该类封装了很多方法，且继承自 Realm 类。
 * 继承 AuthorizingRealm 类后，我们需要重写以下两个方法：
 * doGetAuthenticationInfo() 方法：获取身份信息
 * doGetAuthorizationInfo() 方法：获取权限信息(角色和权限)
 */
public class MyShiroRealm extends AuthorizingRealm { //安全数据源

    @Resource
    private UserService sysUserService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws
            AuthenticationException{
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        User sysUser = sysUserService.findUserByUsrName(usrName);
        if (sysUser == null) {
            throw new UnknownAccountException();//账号错误
        }
        if (sysUser.getUsrFlag()==null || sysUser.getUsrFlag().intValue()==0){
            throw new LockedAccountException(); //账号锁定
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                sysUser,//身份(根据用户名查询数据库获得的用户)
                sysUser.getUsrPassword(),//凭证(查询数据库获得的密码)
                getName()//Realm 对象的名称
        );
        //返回身份信息
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！");
        //获得权限信息
        User sysUser = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //暂不授予权限信息
        return info;
    }
}
